package com.example.fireassistant_server.controller;

import com.example.fireassistant_server.dto.user.*;
import com.example.fireassistant_server.mapper.UserMapper;
import com.example.fireassistant_server.service.UserService;
import com.example.fireassistant_server.vo.UserVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/users")
public class UserController {

    UserService userService;

    UserMapper userMapper;

    //sort的参数名小心写错
//    @GetMapping
//    @ApiOperation("用户检索")
//    @PreAuthorize("hasRole('ROLE_ADMIN')")
//    Page<UserVo> search(@PageableDefault(sort = {"username"}, direction = Sort.Direction.DESC) Pageable pageable) {
////        Pageable page = PageRequest.of(1, 2, Sort.by("id"));
//        System.out.println("已进入");
//        return userService.search(pageable).map(userMapper::toVo);
//    }
    // 按条件搜索用户，区域管理员、总管理员都可以
    @PostMapping("/search")
    @ApiOperation("用户检索")
    Page<UserVo> search(@Validated @RequestBody UserSearchFilter userSearchFilter) {
        return userService.search(userSearchFilter).map(userMapper::toVo);
    }

    // @PostMapping("/") 创建新用户  需要绑定单位名称
    @RequestMapping(method = RequestMethod.POST)
    UserVo create(@Validated @RequestBody UserCreateRequest userCreateDto) {
        return userMapper.toVo(userService.create(userCreateDto));
    }

    //根据id获取user
    @GetMapping("/{id}")
    UserVo get(@PathVariable String id) {
        return userMapper.toVo(userMapper.toDto(userService.get(id)));
    }

    //根据id获取 某个单位下 的所有用户
    @GetMapping("/company/{id}")
    List<UserVo> getByCompanyId(@PathVariable String id){
        return userService.getByCompanyId(id);
    }

    // 根据id更新 user权限
    @PutMapping("/{id}")
    UserVo update(@PathVariable String id,
                  @Validated @RequestBody UserUpdateRequest userUpdateRequest) {
        return userMapper.toVo(userService.update(id, userUpdateRequest));
    }

    // 根据id删除用户；用户表
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_SUPER_ADMIN') or hasRole('ROLE_STATION_ADMIN')")
    void delete(@PathVariable String id) {
        userService.delete(id);
    }

    @GetMapping("/me")
    UserVo me() {
        return userMapper.toVo(userService.getCurrentUser());
    }


    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}
